export default function createShopBus() {
  return {
    events: {},
    //订阅事件
    on(event, callback) {
      if (!this.events[event]) this.events[event] = [];
      this.events[event].push(callback);
    },
    //取消订阅
    off(event, callback) {
      if (!this.events[event]) return;
      if (!callback) this.events[event] = [];
      else {
        const index = this.events[event].indexOf(callback);
        if (index !== -1) this.events[event].splice(index, 1);
      }
    },
    /**
     * 发布事件
     * @param {update} event 
     * @param {
     *    id:"商品id",
     *    name:"商品名"，
     *    num："数量,
     *    unitPrice:"单价"
     * } cartEntity 
     */
    emit(event, cartEntity) {
      let shopCart = getApp().globalData.shopCart
     
      shopCart =  this.addToCart(cartEntity)
      //更新全局购物车
      getApp().globalData.shopCart = shopCart
      //发布事件
      if (this.events[event]){
        this.events[event].forEach((callback) => callback(shopCart))
      }
    },
    /**
     * 加入购物车
     * @param {*} newGoods 
     */
    addToCart(newGoods){
      let shopCart = getApp().globalData.shopCart
      let goodsList = shopCart.goodsList;
      if (goodsList[newGoods.id]) {
        const oldGoods = goodsList[newGoods.id];
        let goodsIdNames = oldGoods.goodsIdNames;
        if (!goodsIdNames[newGoods.name]) {
          goodsIdNames[newGoods.name]={goodsNameNum:0,goodsNamePrice:0}
        }else{
          //nameId：直接添加的nameId没有，故复制原nameId
          newGoods.nameId = goodsIdNames[newGoods.name].nameId
        }
      }else{
        goodsList[newGoods.id]={goodsIdNum: 0,goodsIdMoney: 0,goodsIdNames:{}}
        goodsList[newGoods.id].goodsIdNames[newGoods.name]={goodsNameNum:0,goodsNamePrice:0}
      }
      goodsList[newGoods.id].goodsIdNames[newGoods.name] ={
        goodsNameNum:newGoods.num,//新数量
        goodsNamePrice:newGoods.unitPrice,//新单据
        nameId:newGoods.nameId
      }
      return this.calculateCart(shopCart)
    },
    /**
     * 计算购物车中的金额和数量
     */
    calculateCart(shopCart){
      shopCart.cartNum= 0; //购物车商品合计数量
      shopCart.cartMoney= 0;
      let goodsList = shopCart.goodsList
      for (let goodsId in goodsList) {
        let goodsEntity = goodsList[goodsId]
        goodsEntity.goodsIdNum=0,//数量
        goodsEntity.goodsIdMoney=0//合计价格
        let goodsIdNames = goodsEntity.goodsIdNames;
        for (let goodsIdName in goodsIdNames) {
          let goodsNameEntity =  goodsIdNames[goodsIdName];
          goodsEntity.goodsIdNum = goodsEntity.goodsIdNum + goodsNameEntity.goodsNameNum
          let sumGoodsNameMoney = goodsNameEntity.goodsNameNum * goodsNameEntity.goodsNamePrice
          goodsEntity.goodsIdMoney = goodsEntity.goodsIdMoney + sumGoodsNameMoney
        }
        shopCart.cartNum = shopCart.cartNum + goodsEntity.goodsIdNum
        shopCart.cartMoney = shopCart.cartMoney + goodsEntity.goodsIdMoney
      }
      return shopCart;
    }
  };
}